package com.tvunetworks.center.user.controller;

import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.center.user.model.json.RExtRelation;
import com.tvunetworks.center.user.model.param.DeleteUserFeatureByIdParam;
import com.tvunetworks.center.user.service.*;
import com.tvunetworks.center.user.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @program: tvucc-aggregator
 * @description:
 * @author lebronchen
 * @create: 2020-03-30 15:27
 **/
@RestController
@RequestMapping("/debug")
@Slf4j
public class DebugController {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private UserService userService;

    @Value("${rediskey.cache.superAdminSession}")
    private String superAdminSessionKey;
    @Value("${receiverCentricRedisChannelTopic:CC_Device_Authorization}")
    private String receiverCentricRedisChannelTopic;

    @Autowired
    private RoleManagementService roleManagementService;
    @Autowired
    private UserFeatureService userFeatureService;
    /**
     * 从缓存中获取设备信息
     * @param peerIds peerIds
     * @return Result
     */
    @GetMapping("/listCurrentDevice")
    public Result listCurrentDevice(@RequestParam String peerIds){
        List<Device> devices = deviceService.listCurrentDevice(Arrays.asList(peerIds.split(",")));
        return ResultUtil.success(devices);
    }

    /**
     *
     * @return Result
     */
    @GetMapping("/clearSuperAdminSessionCache")
    public Result clearSuperAdminSessionCache(){
        redisUtil.delete(superAdminSessionKey);
        return ResultUtil.success();
    }

    /**
     *
     * @param message message
     * @return Result
     * @throws IOException 编译异常
     */
    @PostMapping("/notifyDevicePairChange")
    public Result notifyDevicePairChange(@RequestParam String message) throws IOException {
        userDeviceService.notifyDevicePairChange(message);
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @GetMapping("/resetOwner")
    public Result resetOwner() {
        userDeviceService.resetOwner();
        return ResultUtil.success();
    }

    /**
     *
     * @param message message
     * @return Result
     */
    @PostMapping("/receiverCentricRedisChannel")
    public Result receiverCentricRedisChannel(@RequestParam String message) {
        redisUtil.sendMessageToChannel(receiverCentricRedisChannelTopic, message);
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @GetMapping("/listNeedResetRExt")
    public Result listNeedResetRExt() {
        List<RExtRelation> list = userDeviceService.listNeedResetRExt();
        return ResultUtil.success(list);
    }

    /**
     *
     * @param list list
     * @return Result
     */
    @PostMapping("/resetRExt")
    public Result resetRExt(@RequestBody List<RExtRelation> list) {
        userDeviceService.resetRExt(list);
        return ResultUtil.success();
    }

    /**
     *
     * @param token token
     * @return Result
     * @throws IOException 编译异常
     */
    @PostMapping("/getLoginUser")
    public Result getLoginUser(@RequestParam String token) throws IOException {
        Result<LoginUser> loginUser = userService.getLoginUser(token);
        return ResultUtil.success(loginUser);
    }

    /**
     *
     * @param request request
     * @param token token
     * @param checkCookie checkCookie
     * @return Result
     * @throws IOException 编译异常
     */
    @GetMapping("/initLoginUser")
    public Result initLoginUser(HttpServletRequest request, String token, boolean checkCookie) throws IOException {
        //获取token头信息
        token = this.getToken(request, checkCookie);
        if (StringUtils.isBlank(token)) {
            // session为空
            return ResultUtil.error("101", "Token is empty");
        } else {
            // 校验session是否有效
            Result<LoginUser> loginUserResult = userService.getLoginUser(token);
            if (!loginUserResult.assertSuccess()) {
                // session无效
                return ResultUtil.error("102", "Token is invalid", loginUserResult);
            } else {
                return ResultUtil.success(loginUserResult);
            }
        }
    }

    /**
     *
     * @param request request
     * @param checkCookie checkCookie
     * @return String
     */
    public String getToken(HttpServletRequest request, boolean checkCookie){
        String accessToken = null;
        if (checkCookie) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String cookieName = cookie.getName();
                    if("SID".equals(cookieName) && StringUtils.isEmpty(cookie.getValue()) ){
                        continue;
                    }
                    if ("SID".equals(cookieName)) {
                        accessToken = cookie.getValue();
                        log.error("getAccessToken from front Cookie"+accessToken);
                    }
                }
            }

         /*   if(!StringUtils.isEmpty(accessToken) ){
                String authorization = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
                if(!StringUtils.endsWith(authorization,accessToken)){
                    accessToken=null;
                }
            }*/
        }/* else {
            accessToken = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
        }*/
        return accessToken;
    }

    /**
     * 获取roleDevice中的脏数据
     * @return 返回脏数据
     */
  //  @RequestMapping("listDataFromManageRole")
    public Result listDataFromManageRole() {
        return ResultUtil.success(roleManagementService.listDataFromManageRole());
    }

    /**
     * 删除roleDevice中的脏数据并返回结果
     * @param userId userId
     * @return  删除roleDevice中的脏数据并返回结果
     */
  //  @RequestMapping("deleteRoleDevice")
    public Result deleteRoleDevice(@RequestParam("userId") String userId) {
        return ResultUtil.success(roleManagementService.deleteRoleDevice(userId));
    }

    /**
     * 子账号拥有的设备,但是父账号没有该设备,为脏数据,需要移除
     * @return 返回需要删除的设备
     */
 //  @RequestMapping("/listUserDeviceOfDirtyData")
    public Result listUserDeviceOfDirtyData() {
       return ResultUtil.success(userDeviceService.listUserDeviceOfDirtyData());
    }

    /**
     * 删除userDevice中的脏数据
     *
     * @param userId 用户id
     * @param index index
     * @return 返回删除的脏数据
     */
 //   @RequestMapping("/deleteUserDeviceOfDirtyData")
    public Result listUserDeviceOfDirtyData(@RequestParam("userId") String userId, @RequestParam(value = "index", required = false) int index) {
        return ResultUtil.success(userDeviceService.deleteDirtyData(userId, index));
    }


    /**
     * 指定账号删除脏数据
     * @param email email
     * @return 返回删除的脏数据
     */
  //  @GetMapping("/deviceDeleteByEmail")
    public Result deviceDeleteByEmail(@RequestParam("email") String email ) {

        return ResultUtil.success(userDeviceService.deviceDeleteByEmail(email));
    }

    /**
     * 给用户授权Grid_Schedule权限
     * @return null
     */
    @GetMapping("/accreditAllUser")
    public Result accreditAllUser() {

        return ResultUtil.success(userFeatureService.accreditAllUser());
    }

    /**
     * 根据主键id 删除tvu_user_feature中数据
     * @param  param id集合
     * @return null
     */
    @PostMapping("/deleteUserFeatureById")
    public Result deleteUserFeatureById(@RequestBody DeleteUserFeatureByIdParam param) {

        return ResultUtil.success(userFeatureService.deleteUserFeatureById(param.getIds()));
    }

}
